package com.mayisoftware.mayioa.business.po.impl.task;

import com.mayisoftware.mayioa.business.po.api.domain.POImportInfo;
import com.mayisoftware.mayioa.business.po.api.service.IPOUploadService;
import com.mayisoftware.mayioa.common.impl.utils.file.FileUtils;
import com.mayisoftware.mayioa.common.impl.zip.FileUnZipRar;
import com.mayisoftware.mayioa.common.impl.zip.UnZipFile;
import com.mayisoftware.mayioa.platform.api.service.ISysUserService;
import com.mayisoftware.mayioa.platform.impl.util.LogUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 定时任务调度计划解析
 *
 *
 */
@Component("poFileParseTask")
public class POFileParseTask
{
    /**
     * 日志对象
     */
    private static final Logger log = LoggerFactory.getLogger(POFileParseTask.class);

    /**
     * 上传记录操作服务
     */
    @Autowired
    private IPOUploadService uploadService;

    /**
     * 用户管理服务
     */
    @Autowired
    private ISysUserService sysUserService;

    public void parsePOFiles()
    {
        log.info("开始执行工时文件解析");

        try {
            //查询数据库记录
            List<POImportInfo> uploadRecords = uploadService.queryRecordListNeedParse();
            if(CollectionUtils.isEmpty(uploadRecords)){
                log.warn("没有需要解析的工时文件");
                return;
            }

            String errorFilePath = "";
            for (POImportInfo record:uploadRecords){
                boolean isOk = true;
                POImportInfo updateRecord = new POImportInfo();
                try {
                    log.info("处理记录 id: {} 文件:{}",record.getImportId(),record.getFilePath());
                    String filePath = record.getFilePath();

                    File file =new File(filePath);
                    if(!file.exists() || !file.isFile()){
                        log.error("处理记录 id: {} 文件:{}不存在",record.getImportId(),record.getFilePath());
                        continue;
                    }

                    String fileName= file.getName();
                    String fileDir=file.getParentFile().getAbsolutePath();
                    String fileNameNoExt = fileName.substring(0,fileName.lastIndexOf("."));
                    errorFilePath = fileDir+File.separator+fileNameNoExt+".log";

                    updateRecord.setImportId(record.getImportId());
                    //更新DB状态 正在解析
                    updateRecord.setParseStatus("2");

                    uploadService.editInputRecord(updateRecord);


                    StringBuffer planBuffer =new StringBuffer();
                    isOk = analysisOnePOFile(record,file);
                }
                catch (Exception e){
                    log.error("处理记录 id: {} 文件:{},异常",record.getImportId(),record.getFilePath(),e);
                    isOk = false;
                    FileUtils.writeLog(errorFilePath,e.getMessage());
                }
                finally {
                    try {
                        if (isOk){
                            log.info("处理记录 id: {} 文件:{},处理成功",record.getImportId(),record.getFilePath());
                            //更新DB状态 正在解析

                            updateRecord.setParseStatus("3");
                            uploadService.editInputRecord(updateRecord);
                        }
                        else {
                            String err = "处理记录 id: "+record.getImportId()+" 文件:"+record.getFilePath()+",处理失败";
                            log.info(err);
                            //更新DB状态 正在解析
                            updateRecord.setParseStatus("4");
                            updateRecord.setErrorPath(errorFilePath);
                            uploadService.editInputRecord(updateRecord);
                            FileUtils.writeLog(errorFilePath,err);
                        }
                    }
                    catch (Exception e){
                        log.info("处理记录状态异常",e);
                        FileUtils.writeLog(errorFilePath,e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            log.error("执行计划解析异常",e);
        }

    }

    /**
     * 统计分析主方法
     * @param uploadFile PO文件路径
     * @return 0：成功，-1：失败
     */
    private   boolean analysisOnePOFile(POImportInfo updateRecord,File uploadFile){
//        String filePath = uploadFile.getAbsolutePath();
//        File path = new File(filePath);
//        //1.TM项目考勤读取
//        if (!path.isDirectory()){
//            log.error("处理记录 文件:{},不存在！",filePath);
//            return false;
//        }
//
//        List<File> files = FileUtils.getExcelFileList(filePath);
//        if (files.size()==0){
//            log.error("目录{}无有效详单文件。。。！",filePath);
//            return false;
//        }

        if (!uploadService.check(updateRecord,uploadFile)){
            log.error("文件核查失败。。。");
        }
        return  true;
    }

}
